﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Library.CommonClass;

namespace Lamex.mIE.UI
{
    public partial class frmIE_Formula_Check : frmBaseChild
    {
        DataTable dtIE_Formula_Check = null;
        List<ConfigModel> lst = null;
        DataTable dtM = null;

        public frmIE_Formula_Check()
        {
            InitializeComponent();
            //gcFormula_Check.Click+= new EventHandler
        }

        private void frmIE_Formula_Check_Load(object sender, EventArgs e)
        {
            dtIE_Formula_Check = Lamex.Base.BaseBuildSql.GetDataTableBySql(" select * From IE_Formula_Check");
            DataTable dtTemp = dtIE_Formula_Check.Clone();
            dtM = dtIE_Formula_Check.Clone();
            foreach (DataRow dr in dtIE_Formula_Check.Rows)
            {
                DataRow drTemp = dtTemp.NewRow();
                drTemp.ItemArray = dr.ItemArray;
                dtTemp.Rows.Add(drTemp);
                lst = Lamex.Library.CommonClass.ConvertInterface.SetCheckVarValue(dtTemp);
                string funcLogic = GetLogicValue(dr["FORMULA"].ToString());
                dr["RESULT"] = Lamex.Library.CommonClass.ConvertInterface.ExpressConvertValue(funcLogic, lst,true);
                dtTemp.Clear();
                lst.Clear();
            }
            gcFormula_Check.DataSource = dtIE_Formula_Check;
            gvFormula_Check.BestFitColumns();
            gvFormula_Check.OptionsView.ColumnAutoWidth = false;
            gvFormula_Check.OptionsBehavior.Editable = true;

            string str;
            str = IELogicHelper.GetLogicValue("txt1DWG_NO", "txt1Part_No", "txt1Logic");

        }
        string reValue = "";
       
        private void gvFormula_Check_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            //int iRow = gvFormula_Check.FocusedRowHandle;
            //string strFORMULA = gvFormula_Check.GetRowCellDisplayText(iRow, "FORMULA").ToString();
            //string strWIDTH = gvFormula_Check.GetRowCellDisplayText(iRow, "WIDTH").ToString();
            //string strDEPTH = gvFormula_Check.GetRowCellDisplayText(iRow, "DEPTH").ToString();
            //string strHEIGHT = gvFormula_Check.GetRowCellDisplayText(iRow, "HEIGHT").ToString();
            //string strLENGTH = gvFormula_Check.GetRowCellDisplayText(iRow, "LENGTH").ToString();
            //string strTHICK = gvFormula_Check.GetRowCellDisplayText(iRow, "THICK").ToString();

            //MessageBox.Show("表达式：" + strFORMULA + "\r\n" +
            //    "阔度：" + strWIDTH + "\r\n" +
            //    "深度：" + strDEPTH + "\r\n" +
            //    "高度：" + strHEIGHT + "\r\n" +
            //    "长度：" + strLENGTH + "\r\n" +
            //    "厚度：" + strTHICK + "\r\n");

            

            

            try
            {

                //if (gvFormula_Check.FocusedColumn.FieldName == "FORMULA" || gvFormula_Check.FocusedColumn.FieldName == "WIDTH"
                //|| gvFormula_Check.FocusedColumn.FieldName == "DEPTH" || gvFormula_Check.FocusedColumn.FieldName == "HEIGHT"
                //|| gvFormula_Check.FocusedColumn.FieldName == "LENGTH" || gvFormula_Check.FocusedColumn.FieldName == "THICK"
                //)
                //{
                string FORMULA = "";
                double WIDTH = 0;
                double DEPTH = 0;
                double HEIGHT = 0;
                double LENGTH = 0;
                double THICK = 0;
                
               double RESULT = 0;
                string reslutCompare = "";
                int iRow = gvFormula_Check.FocusedRowHandle;
                if (gvFormula_Check.GetRowCellDisplayText(iRow, "FORMULA") != null)
                {
                    if (!string.IsNullOrEmpty(gvFormula_Check.GetRowCellDisplayText(iRow, "FORMULA").ToString()))
                    {
                        FORMULA = gvFormula_Check.GetRowCellDisplayText(iRow, "FORMULA").ToString();
                    }

                }

                if (gvFormula_Check.GetRowCellDisplayText(iRow, "WIDTH") != null)
                {
                    if (!string.IsNullOrEmpty(gvFormula_Check.GetRowCellDisplayText(iRow, "WIDTH").ToString()))
                    {
                        WIDTH = double.Parse(gvFormula_Check.GetRowCellDisplayText(iRow, "WIDTH").ToString());
                        //_WIDTH = gvFormula_Check.GetRowCellDisplayText(iRow, "WIDTH").ToString();
                    }
                }

                if (gvFormula_Check.GetRowCellDisplayText(iRow, "DEPTH") != null)
                {
                    if (!string.IsNullOrEmpty(gvFormula_Check.GetRowCellDisplayText(iRow, "DEPTH").ToString()))
                    {
                        DEPTH = double.Parse(gvFormula_Check.GetRowCellDisplayText(iRow, "DEPTH").ToString());
                        //_DEPTH = gvFormula_Check.GetRowCellDisplayText(iRow, "DEPTH").ToString();
                    }
                }
                if (gvFormula_Check.GetRowCellDisplayText(iRow, "HEIGHT") != null)
                {
                    if (!string.IsNullOrEmpty(gvFormula_Check.GetRowCellDisplayText(iRow, "HEIGHT").ToString()))
                    {
                        HEIGHT = double.Parse(gvFormula_Check.GetRowCellDisplayText(iRow, "HEIGHT").ToString());
                        //_HEIGHT = gvFormula_Check.GetRowCellDisplayText(iRow, "HEIGHT").ToString();
                    }
                }
                if (gvFormula_Check.GetRowCellDisplayText(iRow, "LENGTH") != null)
                {
                    if (!string.IsNullOrEmpty(gvFormula_Check.GetRowCellDisplayText(iRow, "LENGTH").ToString()))
                    {
                        HEIGHT = double.Parse(gvFormula_Check.GetRowCellDisplayText(iRow, "LENGTH").ToString());
                        //_LENGTH = gvFormula_Check.GetRowCellDisplayText(iRow, "LENGTH").ToString();
                    }
                }
                if (gvFormula_Check.GetRowCellDisplayText(iRow, "THICK") != null)
                {
                    if (!string.IsNullOrEmpty(gvFormula_Check.GetRowCellDisplayText(iRow, "THICK").ToString()))
                    {
                        THICK = double.Parse(gvFormula_Check.GetRowCellDisplayText(iRow, "THICK").ToString());
                        //_THICK = gvFormula_Check.GetRowCellDisplayText(iRow, "THICK").ToString();
                    }
                }
                if (gvFormula_Check.GetRowCellDisplayText(iRow, "RESULT") != null)
                {
                    if (!string.IsNullOrEmpty(gvFormula_Check.GetRowCellDisplayText(iRow, "RESULT").ToString()))
                    {
                        reslutCompare = gvFormula_Check.GetRowCellDisplayText(iRow, "RESULT").ToString();
                        //_THICK = gvFormula_Check.GetRowCellDisplayText(iRow, "THICK").ToString();
                    }
                }
                //}
                dtM.Clear();
                DataRow dr = dtM.NewRow();
                dr["FORMULA"] = FORMULA;
                dr["WIDTH"] = WIDTH;
                dr["DEPTH"] = DEPTH;
                dr["HEIGHT"] = HEIGHT;
                dr["LENGTH"] = LENGTH;
                dr["THICK"] = THICK;
                dtM.Rows.Add(dr);

                lst = Lamex.Library.CommonClass.ConvertInterface.SetCheckVarValue(dtM);
                string funcLogic = GetLogicValue(dr["FORMULA"].ToString());
                string result = Lamex.Library.CommonClass.ConvertInterface.ExpressConvertValue(funcLogic, lst, true);
                
                if (result!= reslutCompare)
                    gvFormula_Check.SetFocusedRowCellValue("RESULT", Lamex.Library.CommonClass.ConvertInterface.ExpressConvertValue(funcLogic, lst, true));
                dtM.Clear();
                lst.Clear();




            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }


        public  string GetLogicValue(string FuncLogic)
        {
            try
            { 
            string Msg = FuncLogic;
            string error = ConvertInterface.CheckExpressConvertValue(Msg, lst, true);
            if (!string.IsNullOrEmpty(error))
            {
                return error;
            }
            if (!FuncLogic.Contains("?"))
            {
                string backValue = "";//返回数据大于90009时为90000；否则为原值；
                string dvalue = ConvertInterface.ExpressConvertValue(FuncLogic, lst, true);
                if (double.Parse(dvalue) > 90009)
                    backValue = "900000";
                else
                    backValue = dvalue;
                return backValue;
            }
            string firstIndex = FuncLogic.Substring(0, 1);
            if (firstIndex != "?") return "L1";

            int iCount = FuncLogic.Split(new char[] { ':' }).Length - 1;
            int idx = ConvertInterface.RecFindFirstIndex(FuncLogic, ":");

            if (iCount == 0)
            {
                if (FuncLogic.ToLower().Contains("1/rounddown"))
                {
                    string[] arr = FuncLogic.Split('(');
                    if (arr[0].ToString().ToLower().Trim() != "?1/rounddown") return "Error 1";
                    int idxLeft = ConvertInterface.RecFindFirstIndex(FuncLogic, "(");

                    string strLeft = FuncLogic.Substring(idxLeft, FuncLogic.Length - idxLeft);
                    int idxRight = ConvertInterface.RecFindFirstIndex(strLeft, ")");
                    string strRight = strLeft.Substring(0, idxRight);

                    //double iMin = Convert.ToDouble(ConvertInterface.ExpressConvertValue(strRight, lst, true));
                    //if (iMin < 1) iMin = 1;
                    //(1 / Math.Floor(iMin)).ToString();
                    string backValue = "";//返回数据大于90009时为90000；否则为原值；
                    string dvalue = RecValue(strRight);
                    if (double.Parse(dvalue) > 90009)
                        backValue = "900000";
                    else
                        backValue = dvalue;
                    return backValue;

                    //return RecValue(strRight);
                }
                else
                {
                    string funcLogic = FuncLogic;
                    funcLogic = funcLogic.Replace('?', ' ');

                    string backValue = "";//返回数据大于90009时为90000；否则为原值；
                    string dvalue = ConvertInterface.ExpressConvertValue(funcLogic, lst, true);
                    if (double.Parse(dvalue) > 90009)
                        backValue = "900000";
                    else
                        backValue = dvalue;
                    return backValue;

                    //return ConvertInterface.ExpressConvertValue(funcLogic, lst, true);
                }
            }
            else if (iCount == 1)
            {
                if (!CheckRuleStr(FuncLogic)) return "L1";
                string subLogic = FuncLogic.Replace('?', ' ').Trim();
                string[] strArray = subLogic.Split(':');
                if (strArray.Count() < 2) return "L1";
                //ConfigModel model = lst.Where(p => p.Name == strArray[0].ToString()).FirstOrDefault();
                //if (string.IsNullOrEmpty(model.Num.ToString())) return "L2";
                double midVar = double.Parse(ConvertInterface.ExpressConvertValue(strArray[0].ToString(), lst, true));
                if (ConvertInterface.IsCheckVarStr(strArray[1]))
                {
                    string backValue = "";//返回数据大于90009时为90000；否则为原值；
                    string dvalue = ConvertInterface.GetNorStrValue(midVar, FuncLogic.Substring(idx, FuncLogic.Length - idx), lst);
                    if (double.Parse(dvalue) > 90009)
                        backValue = "900000";
                    else
                        backValue = dvalue;
                    return backValue;

                    //return ConvertInterface.GetNorStrValue(midVar, FuncLogic.Substring(idx, FuncLogic.Length - idx), lst);


                }
                else
                {
                    string backValue = "";//返回数据大于90009时为90000；否则为原值；
                    string dvalue = ConvertInterface.GetStrValue(midVar, strArray[1], lst);
                    if (double.Parse(dvalue) > 90009)
                        backValue = "900000";
                    else
                        backValue = dvalue;
                    return backValue;

                    //return ConvertInterface.GetStrValue(midVar, strArray[1], lst);
                }
            }
            else
            {
                if (!CheckRuleStr(FuncLogic)) return "L1";
                string subLogic = FuncLogic.Replace('?', ' ').Trim();
                string[] strArray = subLogic.Split(':');
                if (strArray.Count() < 1) return "L1";
                //ConfigModel model = lst.Where(p => p.Name == strArray[0].ToString()).FirstOrDefault();
                //if (string.IsNullOrEmpty(model.Num.ToString())) return "L2";

                double midVar = double.Parse(ConvertInterface.ExpressConvertValue(strArray[0].ToString(), lst, true));

                string backValue = "";//返回数据大于90009时为90000；否则为原值；
                string dvalue = ConvertInterface.GetMoreStrValue(midVar, FuncLogic.Substring(idx, FuncLogic.Length - idx), lst);
                if (double.Parse(dvalue) > 90009)
                    backValue = "900000";
                else
                    backValue = dvalue;
                return backValue;


                //return ConvertInterface.GetMoreStrValue(midVar, FuncLogic.Substring(idx, FuncLogic.Length - idx), lst);
            }

            return "L1";
        }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message+":"+ FuncLogic);
                return "";
            }
        }

        public static bool CheckRuleStr(string FunLogic)
        {
            int m = 0;
            string strCheck = @"@?:,.+*-/|()WDW1D1W2D2THL12345678910";

            foreach (char c in FunLogic)
            {
                if (!strCheck.Contains(c))
                    m++;
            }
            if (m != 0) return false;
            return true;
        }

        private  string RecValue(string Logic)
        {
            double iMin = Convert.ToDouble(ConvertInterface.ExpressConvertValue(Logic, lst, true));
            if (iMin < 1) iMin = 1;
            return (1 / Math.Floor(iMin)).ToString();
        }

        private void gcFormula_Check_KeyUp(object sender, KeyEventArgs e)
        {
           
        }

        private void gcFormula_Check_TextChanged(object sender, EventArgs e)
        {
           
        }

        private void gcFormula_Check_MouseUp(object sender, MouseEventArgs e)
        {
           
        }
    }
}